package com.example.computer_exam_training_sys.mapper;

import com.example.computer_exam_training_sys.entity.QuestionCommentInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface QuestionCommentMapper {
    @Insert("INSERT INTO question_comments (question_id, user_id, content) " +
            "VALUES (#{questionId}, #{userId}, #{content})")
    @Options(useGeneratedKeys = true, keyProperty = "commentId")
    int insertComment(QuestionCommentInfo comment);

    @Update("UPDATE question_comments SET status = 0 WHERE comment_id = #{commentId}")
    int deleteComment(Integer commentId);

    @Select("SELECT * FROM question_comments WHERE status = 1 ORDER BY create_time DESC")
    List<QuestionCommentInfo> getAllComments();

    @Select("SELECT * FROM question_comments WHERE question_id = #{questionId} AND status = 1 ORDER BY create_time DESC")
    List<QuestionCommentInfo> getCommentsByQuestionId(Integer questionId);

    @Select("SELECT * FROM question_comments WHERE status = 1 AND (content LIKE CONCAT('%',#{search},'%') OR comment_id = #{search}) ORDER BY create_time DESC LIMIT #{offset}, #{size}")
    List<QuestionCommentInfo> searchComments(@Param("search") String search, @Param("offset") int offset, @Param("size") int size);

    @Select("SELECT COUNT(*) FROM question_comments WHERE status = 1 AND (content LIKE CONCAT('%',#{search},'%') OR comment_id = #{search})")
    int countSearchComments(@Param("search") String search);

    @Select("SELECT * FROM question_comments WHERE status = 1 ORDER BY create_time DESC LIMIT #{offset}, #{size}")
    List<QuestionCommentInfo> getCommentsWithPagination(@Param("offset") int offset, @Param("size") int size);

    @Select("SELECT COUNT(*) FROM question_comments WHERE status = 1")
    int countAllComments();

    @Update({
            "<script>",
            "UPDATE question_comments SET status = 0 WHERE comment_id IN",
            "<foreach collection='commentIds' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    int batchDeleteComments(@Param("commentIds") List<Integer> commentIds);

    @Select("SELECT * FROM question_comments WHERE topic_id = #{topicId} AND status = 1 ORDER BY create_time DESC")
    List<QuestionCommentInfo> getCommentsByTopicId(@Param("topicId") Integer topicId);
}